//
//  KKImageBrowser.m
//  KKImageBrowser_Example
//
//  Created by Hansen on 11/18/21.
//  Copyright © 2021 chenghengsheng. All rights reserved.
//

#import "KKImageBrowser.h"
#import "KKImageBrowserContainerView.h"
#import "UIView+KKImageBrowser.h"

@interface KKImageBrowser ()

@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) KKImageBrowserContainerView *containerView;
/* indexLabel */
@property (nonatomic, strong) UILabel *indexLabel;
/* saveButton */
@property (nonatomic, strong) UIButton *saveButton;

@end

@implementation KKImageBrowser

- (instancetype)init {
    if (self = [super init]) {
        self.modalPresentationStyle = UIModalPresentationFullScreen;
        self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.bgImageView];
    UIImage *bgImage = [UIApplication sharedApplication].keyWindow.screenshotsImage;
    self.bgImageView.image = bgImage;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showImageBrowser];
        [self.view addSubview:self.indexLabel];
        [self.view addSubview:self.saveButton];
    });
}

- (void)needUpdateIndex:(NSInteger )index{
    
    self.indexLabel.text = [NSString stringWithFormat:@"%ld / %ld",index + 1,self.images.count];
}

- (void)showImageBrowser {
    KKImageBrowserContainerView *containerView = [[KKImageBrowserContainerView alloc] init];
    containerView.images = self.images;
    containerView.index = self.index;
    __weak typeof(self) weakSelf = self;
    containerView.whenDidHideImageBrowser = ^{
        [weakSelf dismissViewControllerAnimated:NO completion:nil];
    };
    containerView.whenChangeBackgroundAlpha = ^(CGFloat alpha) {
        //TODO
    };
    containerView.whenNeedUpdateIndex = ^(NSInteger index) {
        weakSelf.index = index;
//        [weakSelf needUpdateIndex:index];
    };
    [containerView showToView:self.view];
    self.containerView = containerView;
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    CGRect bounds = self.view.bounds;
    self.bgImageView.frame = bounds;
}

- (void)toPopBack {
    [self.containerView removeShow];
}

#pragma mark - setters

- (void)setIndex:(NSInteger)index {
    _index = index;
    [self needUpdateIndex:index];
}

#pragma mark - getters

- (UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] init];
    }
    return _bgImageView;
}

- (UILabel *)indexLabel {
    if (!_indexLabel) {
        _indexLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, kScreenHeight-kBottomSafeHeight-40, kScreenWidth, 40)];
        _indexLabel.textColor = [UIColor appWhiteLabelColor];
        _indexLabel.font = [UIFont systemFontOfSize:16];
        _indexLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _indexLabel;
}

- (UIButton *)saveButton {
    if (!_saveButton) {
        _saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _saveButton.frame = CGRectMake(kScreenWidth-66, kStatusBarHeight, 50, 44);
        [_saveButton setTitle:@"保存" forState:UIControlStateNormal];
        [_saveButton setTitleColor:[UIColor appWhiteLabelColor] forState:UIControlStateNormal];
        _saveButton.titleLabel.font = [UIFont systemFontOfSize:16];
        __weak __typeof(&*self)weakSelf = self;
        [[_saveButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            KKImageBrowserModel *model = weakSelf.images[weakSelf.index];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:model.url]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self savePhotoWithImage:image];
            });
            
        }];
    }
    return _saveButton;
}

//图片保存
- (void)savePhotoWithImage:(UIImage *)image {
//    NSLog(@"%s",__func__);
    //对图片进行存储
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if(error){
        //失败
        NSLog(@"%@",@"失败");
        [self.view makeToast:@"保存失败"];
    }else{
        //成功
        NSLog(@"%@",@"成功");
        [self.view makeToast:@"保存成功"];
    }
}

@end
